 #define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    bool vis[16][16];
    int dx[4] = { 0, 0, -1, 1 };
    int dy[4] = { 1, -1, 0, 0 };
    int m, n;
    int ret;

    int getMaximumGold(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                //对每个位置进行深度优先遍历
                if (grid[i][j])
                {
                    vis[i][j] = true;
                    dfs(grid, i, j, grid[i][j]);
                    //还原现场
                    vis[i][j] = false;
                }
            }

        return ret;
    }

    //path为到目前位置的路径的所有数的和
    void dfs(vector<vector<int>>& grid, int i, int j, int path)
    {
        ret = max(ret, path);
        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y])
            {
                vis[x][y] = true;
                dfs(grid, x, y, path + grid[x][y]);
                //还原现场
                vis[x][y] = false;
            }
        }
    }
};

class Solution {
public:
    bool vis[21][21];
    int dx[4] = { 0, 0, -1, 1 };
    int dy[4] = { 1, -1, 0, 0 };
    int m, n, step;
    int ret;

    int uniquePathsIII(vector<vector<int>>& grid) {
        m = grid.size(), n = grid[0].size();
        int bx = 0, by = 0;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                if (grid[i][j] == 0) step++;
                else if (grid[i][j] == 1) bx = i, by = j;
            }
        step += 2;//这里加上入口和出口位置
        vis[bx][by] = true;
        dfs(grid, bx, by, 1);
        return ret;
    }

    void dfs(vector<vector<int>>& grid, int i, int j, int count)
    {
        if (grid[i][j] == 2)
        {
            //判断是否合法
            if (step == count) ret++;
            return;
        }

        for (int k = 0; k < 4; k++)
        {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] != -1)
            {
                vis[x][y] = true;
                dfs(grid, x, y, count + 1);
                //恢复现场
                vis[x][y] = false;
            }
        }
    }
};